import {getRecommendationAddress, setAddress} from "../../utils/settings";

const app = getApp()
const plugin = requirePlugin("WechatSI")
const manager = plugin.getRecordRecognitionManager()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        testMessageDetail: {
            data: []
        },
        scores: {},
        myStage: "",
        totalScores: 0,
        isLoading: false,
        reScoreMode:{},
        canClickSports: true,
        canClickselfLiving: true,
        canClicklivingAdapt: true,
        backfrom:'',
        userInfo:{},
        myPlan: {},
        // 评论和回复内容
        reply_content: "",
        voice_content: "",
        top_value: 100,
        // 最大行数
        max_length: 0,
    },

    // isMore true 用于上拉刷新
    loadMessage: async function (query) {
        //列表中增加用户发送内容
        if (!this.data.isLoading) {
            this.setData({isLoading: true})
        }
        let seconds = new Date().getSeconds();
        let minutes = new Date().getMinutes();
        let hours = new Date().getHours();
        let timestamp = hours + ':' + minutes + ':' + seconds
        var slot = true
        if (!slot) {
            wx.showToast({
                title: '获取信息失败',
                icon: 'error'
            })
            return false
        }
        var userTmp = {
            self: 1,
            showTime: 1,
            string_time: timestamp,
            target_user: {
                username: 'user',
                avatar: '../image/user.png'
            },
            content: query.query,
        }
        this.data.testMessageDetail.data.push(userTmp)
        var test = this.data.testMessageDetail.data
        this.setData({
            testMessageDetail: this.data.testMessageDetail,
        });

        //列表中增加机器人回答内容
        var answer = this.anaText(query.query)
        if (answer.myType !== "无达成") {


            var myContent = "";
            var remark;
            if (answer.myType == "康复阶段达成"){
                remark = [
                    {title:"运动功能", src:"to_sports"},
                    {title:"生活自理", src:"to_life"},
                    {title:"社会适应", src:"to_soical"}]
                if (answer.myItem =="运动功能")
                    myContent = "检测到您在运动康复领域已经达成康复目标，如需制定新的康复计划，请完成以下评估";
                if (answer.myItem =="生活自理")
                    myContent = "检测到您在生活自理能力康复领域已经达成康复目标，如需制定新的康复计划，请完成以下评估";
                if (answer.myItem =="社会适应")
                    myContent = "检测到您在社会适应能力康复领域已经达成康复目标，如需制定新的康复计划，请完成以下评估";
            }
            if (answer.myType == "训练项目达成"){
                if (answer.myItem =="运动功能"){
                    myContent = "检测到您在运动康复领域取得新的进展，请您重新进行社会适应能力的评估，我将为您制定新的计划";
                    remark = [{title:"运动功能", src:"to_sports"}]
                    this.data.canClicklivingAdapt = false
                    this.data.canClickselfLiving = false
                }
                if (answer.myItem =="生活自理"){
                    myContent = "检测到您在生活自理能力康复领域取得新的进展，请您重新进行社会适应能力的评估，我将为您制定新的计划";
                    remark = [{title:"生活自理", src:"to_life"}]
                    this.data.canClicklivingAdapt = false
                    this.data.canClickSports = false
                }
                if (answer.myItem =="社会适应"){
                    myContent = "检测到您在社会适应能力康复领域取得新的进展，请您重新进行社会适应能力的评估，我将为您制定新的计划";
                    remark = [{title:"社会适应", src:"to_soical"}]
                    this.data.canClickSports = false
                    this.data.canClickselfLiving = false
                }
            }
            var botTmp = {
                self: 0,
                showTime: 0,
                string_time: '',
                target_user: {
                    username: 'bot',
                    avatar: '../image/bot.jpg'
                },
                content: myContent,
            }
            this.sendReply(botTmp)
            var botTmp = {
                self: 0,
                showTime: 0,
                string_time: '',
                target_user: {
                    username: 'bot',
                    avatar: '../image/bot.jpg'
                },
                have_remark: true,
                content: "",
                remark: remark
            }
            this.sendReply(botTmp)

        }
        this.setData({
            isLoading: false
        })
        return true
    },
    sendReply(botTmp){
        //机器人回答

        this.getMaxLength(botTmp.content)
        this.setData({
            top_value: this.data.max_length * 2,
        });
        this.data.testMessageDetail.data.push(botTmp)
        var test = this.data.testMessageDetail.data
        this.setData({
            testMessageDetail: this.data.testMessageDetail,
        });
    },
    onLoad: async function () {
        this.initScores()
        this.initRecord()
    },
    onShow(options) {
        this.setData({
            userInfo: wx.getStorageSync("userInfo")
        })
        if(this.data.backfrom == "社会适应"){
            this.setData({
                canClicklivingAdapt: false
            })
        }
        if(this.data.backfrom == "运动功能"){
            this.setData({
                canClickSports: false
            })
        }
        if(this.data.backfrom == "生活自理"){
            this.setData({
                canClickselfLiving: false
            })
        }
        if(this.data.canClickSports==false && this.data.canClickselfLiving==false && this.data.canClicklivingAdapt==false){
            //完成所有评估，进入下一步
            this.endAndShowPlan()
        }
    },
    endAndShowPlan(){
        //重新计算分数
        var newTotal = 0;
        console.log(getApp())
        // var newScores = JSON.parse(JSON.stringify(app.globalData.scores)) 
        var newScores = JSON.parse(JSON.stringify(this.data.userInfo.score))
        for(var o in newScores){
            newTotal += newScores[o]
        }
        var plusScore = newTotal - this.data.totalScores;
        this.data.totalScores = newTotal
        //组织回答语言
        var myContent = ''
        var cardInfo = {}
        if(this.data.reScoreMode.myType=="训练项目达成"){
            myContent = '已完成评估，分数是'+newTotal+'分，较上次评估增加'+plusScore+'分，已根据您的进展为您重新制定康复计划'
            this.getPlan()
        }else if(this.data.reScoreMode.myType=="康复阶段达成"){
            myContent = '已完成评估，分数是'+newTotal+'分，较上次评估增加'+plusScore+'分，';
            if (plusScore>0 ){
                if (newTotal>28){//末期
                    myContent += "恭喜您进入康复末期阶段，已根据您的进展为您重新制定康复计划"
                    this.data.myStage = "末期"
                }else if (newTotal>20){//中期
                    myContent += "恭喜您进入康复中期阶段，已根据您的进展为您重新制定康复计划"
                    this.data.myStage = "中期"
                }else if (newTotal>10){//初期
                    myContent += "恭喜您进入康复初期阶段，已根据您的进展为您重新制定康复计划"
                    this.data.myStage = "初期"
                }
                app.globalData.myStage = this.data.myStage
                cardInfo = this.getPlan()
            }else{
                myContent += "建议重新测试"
            }
        }
        var botTmp = {
            self: 0,
            showTime: 0,
            string_time: '',
            target_user: {
                username: 'bot',
                avatar: '../image/bot.jpg'
            },
            content: myContent,
        }
        this.sendReply(botTmp)
        
        
        this.setData({
            canClickSports: true,
            canClickselfLiving: true,
            canClicklivingAdapt: true
        })


    },
    getPlan(){
        var that = this
        let thisUserInfo = wx.getStorageSync("userInfo")
        wx.setStorageSync('changed', 0)
        let evaluation = thisUserInfo.score
        evaluation.evaluateStage =thisUserInfo.record.behaviorPhase
        console.log(evaluation)
        let dataset = {
            "sex": thisUserInfo.record.gender,
            "age": thisUserInfo.record.age,
            "disabilityType": thisUserInfo.record.disabilityType,
            "disabilityCause": thisUserInfo.record.disabilityCause,
            "disabilityLevel": thisUserInfo.record.disabilityLevel,
            "evaluation": evaluation
        }
        wx.request({
            url: getRecommendationAddress,
            data: dataset,
            method: "POST",
            success(res){
                console.log(res.data)
                that.data.myPlan = res.data
                that.data.userInfo.plan = res.data
                wx.request({
                    url: setAddress,
                    data: that.data.userInfo,
                    method: "POST",
                    success:(res)=>{
                        wx.setStorageSync('userInfo', that.data.userInfo)
                    },
                    fail:(err)=>{
                      wx.showToast({
                        title: '保存失败',
                        icon: 'error'
                      })
                      console.log(err)
                    }
                  })
                var botTmp = {
                    self: 0,
                    showTime: 0,
                    string_time: '',
                    target_user: {
                        username: 'bot',
                        avatar: '../image/bot.jpg'
                    },
                    have_card: true,
                    content: '',
                    card_info:res.data
                }
                that.sendReply(botTmp)
            }
        })
    },
    getMaxLength: function (text) {
        // 利用回车数量以及字数判断高度
        var enter_count = 0
        for (let t of text) {
            if (t === '\n') {
                enter_count++;
            }
        }
        var max = (enter_count + text.length / 13) * 72
        if (max > this.data.max_length) {
            this.data.max_length = max
        }
    },
    // 提交回复
    submitReply: async function (e) {
        // 消息为空
        if (!/[^\s]+/.test(this.data.reply_content)) {
            this.setData({
                reply_content: ""
            });
            wx.showToast({
                title: "消息为空",
                icon: "error"
            })
            return;
        }
        // TODO: 在线更新该回复
        const res = this.loadMessage({
            query: this.data.reply_content
        })
        if (!res) {
            wx.showToast({
                title: "发送失败",
                icon: "error"
            })
            return
        }
        this.setData({
            reply_content: ""
        })
    },
    // 评论内容刷新
    replyInputChange: function (e) {
        this.setData({
            reply_content: e.detail.value
        })
    },

    streamRecord: function () {
        manager.start({
            lang: 'zh_CN',
        })
    },
    streamRecordEnd: function () {
        manager.stop()
    },
    initScores: function () {
        //获取用户分数
        //现在采用静态的值做演示
        this.setData({
            scores: this.data.userInfo.score,
            myStage: this.data.userInfo.record.behaviorPhase
        })
        //这里以后从数据库获取

        this.data.userInfo.score = this.data.scores
        app.globalData.myStage = this.data.myStage
        var total = 0
        for(var o in this.data.scores){
            total += this.data.scores[o]
        }
        this.data.totalScores = total

    },
    initRecord: function () {
        //下面是语音识别部分
        //有新的识别内容返回，则会调用此事件
        manager.onRecognize = (res) => {
            let text = res.result
            this.setData({
                currentText: text,
            })
        }
        // 识别结束事件
        manager.onStop = (res) => {
            let text = res.result
            if (text == '') {
                // 用户没有说话，可以做一下提示处理...
                return
            }
            this.loadMessage({
                query: text
            })
            console.log(text)
        }
    },
    //以下是跳转页面
    to_soical() {
        this.setData({
            canClicklivingAdapt: false,
            backfrom:'社会适应'
        })
        wx.navigateTo({
            url: "../tagInput/tagInput?type=社会适应"
        })
    },
    to_sports() {
        this.setData({
            canClickSports: false,
            backfrom:'运动功能'
        })
        wx.navigateTo({
            url: "../tagInput/tagInput?type=运动功能"
        })
    },
    to_life() {
        this.setData({
            canClickselfLiving: false,
            backfrom:'生活自理'
        })
        wx.navigateTo({
            url: "../tagInput/tagInput?type=生活自理"
        })
    },
    //以下是处理逻辑
    anaText(text){
        //该函数用于分析用户语句是否触发评估判定
        var trigger_list = ["可以","独立","能"]
        var sportTrainingItems = ["翻身", "坐", "站", "转移", "上下台阶"]
        var selfLivingTrainingItems = ["进食", "穿脱衣物", "做家务" ,"步行或驱动轮椅"]
        var livingAdaptTrainingItems = ["洗漱", "入厕", "交流","社会活动"]
        var sportTarget_list = ["增强肌肉力量","可以自己行走","运动功能改善，能进行简单的身体锻炼","可做简单运动"]
        var selfLivingTarget_list = ["可以自主吃饭","能完成日常的吃饭穿衣","独立外出","可以做简单的家务"]
        var livingAdaptTarget_list = ["提高生活适应能力","可以参与社会活动","逐渐提高，与人进行日常交流","可以参与社区活动"]
        var rtn = {myType:"无达成", myItem:""}
        if (this.isIn(text, trigger_list)){
            //触发重新评估函数
            console.log("触发重新评估函数")
            if (this.isIn(text, sportTarget_list))
                rtn = {myType:"康复阶段达成", myItem:"运动功能"}
            if (this.isIn(text, selfLivingTarget_list))
                rtn = {myType:"康复阶段达成", myItem:"生活自理"}
            if (this.isIn(text, livingAdaptTarget_list))
                rtn = {myType:"康复阶段达成", myItem:"社会适应"}
            if (this.isIn(text, sportTrainingItems))
                rtn = {myType:"训练项目达成", myItem:"运动功能"}
            if (this.isIn(text, selfLivingTrainingItems))
                rtn = {myType:"训练项目达成", myItem:"生活自理"}
            if (this.isIn(text, livingAdaptTrainingItems))
                rtn = {myType:"训练项目达成", myItem:"社会适应"}
        }
        this.data.reScoreMode =rtn
        return rtn
    },
    isIn(str, list){
        //该函数用于判定list数组中是否包含str字符串
        for(var i=0;i<list.length;i++){
            if (str.indexOf(list[i]) !== -1){
                return true
            }
        }
        return false
    },
    reScore(){
        //重新评估
    }
})


